﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using WebProject.Core.Models;

namespace WebProject.Core.Repositories
{
    public abstract class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class, IEntity
    {
        #region[Private Attribute]
        private readonly EfDbContext m_dbContext;
        #endregion

        #region[Constructor]
        protected GenericRepository(EfDbContext dbContext)
        {
            if (dbContext != null)
            {
                m_dbContext = dbContext;
            }
            else
            {
                throw new ArgumentNullException("dbContext");
            }
        }
        #endregion

        protected DbSet<TEntity> DbSet
        {
            get { return m_dbContext.Set<TEntity>(); }
        }

        #region[Implement Methods]
        public int Add(TEntity entity)
        {
            DbSet.Add(entity);
            return m_dbContext.SaveChanges();
        }

        public int Remove(TEntity entity)
        {
            DbSet.Remove(entity);
            return m_dbContext.SaveChanges();
        }

        public int Update(TEntity entity)
        {
            var entry = m_dbContext.Entry(entity);
            if (entry.State == EntityState.Detached)
            {
                //DbSet.Attach(entity);
                entry.State = EntityState.Modified;
                //var entityToUpdate = FindById(entity.Id);
                //EmitMapper.ObjectMapperManager.DefaultInstance.GetMapper<TEntity, TEntity>().Map(entity, entityToUpdate);
            }
            return m_dbContext.SaveChanges();
        }

        public IList<TEntity> GetAll()
        {
            return DbSet.ToList();
        }

        public TEntity GetById(int id)
        {
            return DbSet.SingleOrDefault(entity => entity.Id == id);
        }
        #endregion
    }
}
